package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("login")
    public String login(String name, String pwd, HttpServletRequest req) {
        UserBean user = userService.login(name, pwd);
        if (user != null) {
            req.getSession().setAttribute("loginUser", user);
            return "ok";
        } else {
            return "no";
        }
    }

    @RequestMapping("updatePwd")
    public String updatePwd(String pwd, String newPwd, HttpServletRequest req) {
        UserBean userBean = (UserBean) req.getSession().getAttribute("loginUser");
        if (userBean != null && userBean.getPwd().equals(pwd)) {
            userService.updateUserPwd(userBean.getId(), newPwd);
            return "ok";
        } else {
            return "no";
        }
    }

    @RequestMapping("add")
    public String add(UserBean userBean) {
        boolean flag = userService.addUser(userBean);
        if (flag) {
            return "ok";
        } else {
            return "no";
        }
    }

    @RequestMapping("updateLevel")
    public String updateLevel(Integer id, String level) {
        userService.updateUserLevel(id, level);
        return "ok";
    }

    @RequestMapping("findById")
    public UserBean findById(Integer id) {
        return userService.findById(id);
    }

    @RequestMapping("del")
    public String del(Integer id, HttpServletRequest req) {
        UserBean userBean = (UserBean) req.getSession().getAttribute("loginUser");
        boolean flag = userService.delUser(id, userBean);
        if (flag) {
            return "ok";
        } else {
            return "no";
        }
    }

    @RequestMapping("findAll")
    public List<UserBean> findAll() {

        return userService.findAll();
    }

    @RequestMapping("checkName")
    public String checkName(String name) {
        boolean flag = userService.checkName(name);
        if (flag) {
            return "ok";
        } else {
            return "no";
        }
    }

    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req) {

        return (UserBean) req.getSession().getAttribute("loginUser");
    }
}
